package com.example.administrator.threaduidemo;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 主线程和子线程的交互
 */
public class MainActivity extends AppCompatActivity  implements View.OnClickListener{

    @BindView(R.id.btn_handler)
    Button btnHandler;
    @BindView(R.id.tv_handler)
    TextView tvHandler;
    @BindView(R.id.btn_asyncTask)
    Button btnAsyncTask;
    @BindView(R.id.tv_AsyncTask)
    TextView tvAsyncTask;
    @BindView(R.id.btn_runOnUIThread)
    Button btnRunOnUIThread;
    @BindView(R.id.tv_runOnUIThread)
    TextView tvRunOnUIThread;
    @BindView(R.id.btn_Post)
    Button btnPost;
    @BindView(R.id.tv_Post)
    TextView tvPost;
    @BindView(R.id.btn_PostDelayed)
    Button btnPostDelayed;
    @BindView(R.id.tv_PostDelayed)
    TextView tvPostDelayed;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    private final  int HANDLERNUM = 101;
    private MyThread thread;
    private Button btn_sd;
    private MapView mMapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        btn_sd = (Button) findViewById(R.id.btn_sd);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        BaiduMap mBaiduMap  = mMapView.getMap();
        //普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        initListener();
        thread = new MyThread();

    }
    /**
     * 注册点击事件
     */
    public void initListener(){
        btnHandler.setOnClickListener(this);
        btnAsyncTask.setOnClickListener(this);
        btnPost.setOnClickListener(this);
        btnPostDelayed.setOnClickListener(this);
        btnRunOnUIThread.setOnClickListener(this);
        btn_sd.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.btn_handler:
                new Thread(thread).start();
                break;
            //asycnTask轻量级的线程间通信，只能执行一次，执行多次会出现异常
            case R.id.btn_asyncTask:
                //调用asyncTask
                MyAsycnTask myAsycnTask = new MyAsycnTask(MainActivity.this);
                try {
                    myAsycnTask.execute(new URL("http://www.crazyit.org/ethos.php"));
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_runOnUIThread:
                onUiThread();
                break;
            case R.id.btn_Post:
               // Log.i("mhysa-->",tvPost.getHeight()+"....");
                tvPost.post(new Runnable() {
                    @Override
                    public void run() {
                        new MyPostThread().start();
                        tvPost.setText(msg);
                    }
                });
                break;
            /**
             * 1000表示延时时间，可以用来做定时器
             */
            case R.id.btn_PostDelayed:
                myhandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new MyPostThread().start();
                        tvPostDelayed.setText(msg);
                    }
                },1000);
                break;
            case R.id.btn_sd:
                btn_sd.setText(getSdcardDir());
                Log.i("mhysa",getSdcardDir());
                break;
        }
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
       /* Log.i("mhysa","返回的路径："+Environment.getExternalStorageDirectory().toString());
        return Environment.getExternalStorageDirectory().toString();*/
    }

    /**
     * POST
     */
    private String msg;
    public class MyPostThread extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
                msg = "来自post子线程";
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * AsycnTask
     * URL:启动任务执行的输入参数类型
     * Integer:后台任务完成的进度值类型
     * String:后台执行任务完成后返回结果的类型
     * 待完成：解析数据
     */
    public class MyAsycnTask extends AsyncTask<URL,Integer,String>{

        ProgressDialog progressDialog;
        private Context context;
        //定义记录已经读取的行数
        private int hasRead = 0;
        MyAsycnTask(Context context){
            this.context = context;
        }

        //在doInBackground之后系统会自动调用,并将doInBackground()方法的返回值传给这个方法

        @Override
        protected void onPostExecute(String s) {
            tvAsyncTask.setText(s);
            progressDialog.dismiss();
        }

        //后台线程将要完成的任务
        @Override
        protected String doInBackground(URL... params) {
            /**
             * 下载任务
             */
            StringBuilder sb = new StringBuilder();
            try {
                URLConnection conn = params[0].openConnection();
                //打开connection输入流,并将它包装成bufferReader
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
                String line =null;
                while ((line = br.readLine())!=null){
                    sb.append(line+"\n");
                    hasRead++;
                    publishProgress(hasRead);
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        //在doInBackground()方法中调用publishProgress()方法更新任务的执行进度够，将会触该方法
        @Override
        protected void onProgressUpdate(Integer... values) {
            //更新进度
            tvAsyncTask.setText("已经读取了"+values[0]+"行！");
            progressDialog.setProgress(values[0]);
        }
        //执行后台耗时操作前被调用
        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("任务执行中");
            progressDialog.setMessage("任务正在执行，请稍等。。。");
            //不能取消
            progressDialog.setCancelable(false);
            //设置最大值
            progressDialog.setMax(200);
            //对话框风格
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setIndeterminate(false);
            progressDialog.show();
        }
    }

    /**
     * handler实现线程间通信
     */
    private String handler;

    Handler myhandler = new Handler(){

        @Override
        public void handleMessage(Message msg) {
            if(msg.what == HANDLERNUM){
                handler =  msg.getData().getString("handler");
                tvHandler.setText(handler);
            }
        }
    };


    class  MyThread implements  Runnable{
        @Override
        public void run() {

            Message msg =Message.obtain();
            msg.what = HANDLERNUM;
            Bundle bundle = new Bundle();
            bundle.putString("handler","handler发送来的消息");
            msg.setData(bundle);

            myhandler.sendMessage(msg);
        }


    }
    /**
     * ruOnuiThread
     */
    public   void onUiThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvRunOnUIThread.setText("通过runOnUiThread方式传递数据");
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
